import React, { useState ,useRef} from 'react'
import { Button, Form, Input, Modal } from 'antd';
import API from '../api';
import {useSelector} from 'react-redux';
import Forms from "../form"

export default function PassFind({ to_login }) {
  const [mail,setMail]=useState('')
  const languages = useSelector((state) =>state).publicReducer.language
  const onFinish = async (values) => {
    console.log('Success:', values);
    let res = await API.login()
    let result = res.data.filter(item => item.mail === values.Email)
    setMail(values.Email)
    if (result.length!==0) {
      setIsModalOpen(true)
      setStatus('true')
      await API.changePass(result[0].id)
    } else {
      setStatus('false')
      setIsModalOpen(true)
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const [isModalOpen, setIsModalOpen] = useState(false)
  const [ModalOpen, setModalOpen] = useState(false)
  const [status, setStatus] = useState('false')
  const handleCancel = () => {
    setIsModalOpen(false)
  }
  const handleOk =async () => {
    console.log(newPass,'newPass');
    let res = await API.login();
    let result = res.data.filter(item => item.mail === mail&&item.password===newPass)
    console.log(result,'result')
    if (result.length!==0) {
      setIsModalOpen(false)
      setModalOpen(true)
    } else {
      setIsModalOpen(true)
      setMsg(true)
    }
  }
  const [newPass,setNewPass]=useState('')
  const [msg,setMsg]=useState(false)
  

  const forms = useRef();

  return (
    <div className='passFind'>
      <hgroup>{languages==="Korean"?"해당 Email로 임시 비밀번호를 발송합니다.":(languages==="Chinese"?"通过电子邮件发送临时密码。":"Send a temporary password by email.")}</hgroup>
      <Form
        name="basic"
        labelCol={{
          span: 6,
        }}
        wrapperCol={{
          span: 14,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <section>{languages==="Korean"?"아이디":(languages==="Chinese"?"ID":"ID")}</section>
        <Form.Item
          name="Email"
        >
          <Input placeholder='Email' />
        </Form.Item>
        <p>{languages==="Korean"?"이메일주소를 입력하세요":(languages==="Chinese"?"请输入您的电子邮件地址":"Please enter your email address")}</p>


        <Form.Item
          wrapperCol={{
            offset: 10,
          }}
        >
          <Button type="primary" htmlType="submit">
          {languages==="Korean"?"발송":(languages==="Chinese"?"发送":"send")}
          </Button>
        </Form.Item>
      </Form>


      <Modal className='modal_pass' open={isModalOpen} onCancel={handleCancel} onOk={handleOk} footer={null} centered>
        {
          status ==="true"
          ? 
          <div className='success'>
            <hgroup>{languages==="Korean"?"아래의 ID로 임시 비밀번호를 발송하였습니다.":(languages==="Chinese"?"已使用以下ID发送临时密码。":"The temporary password has been sent with the following ID.")}</hgroup>

            <aside>hongildong@naver.com</aside>

            <span>{languages==="Korean"?"비밀번호":(languages==="Chinese"?"密码":"password")}</span>

            <Input.Password onChange={(e)=>setNewPass(e.target.value)} />
            {msg?<p>{languages==="Korean"?"비밀번호가 맞지 않습니다.":(languages==="Chinese"?"密码不正确":"The password is incorrect.")}</p>:<></>}

            <hgroup>{languages==="Korean"?"로그인 후 비밀번호를 변경해 주세요.":(languages==="Chinese"?"登录后请更改密码。":"Please change your password after logging in.")}</hgroup>

            <Button onClick={()=>to_login()}>{languages==="Korean"?"로그인":(languages==="Chinese"?"登录":"Sign in")}</Button>

            <Button onClick={handleOk}>{languages==="Korean"?"확인":(languages==="Chinese"?"确认":"confirm")}</Button>
          </div> 
          : 
          <div className='error'>
            <aside>{languages==="Korean"?"입력하신 정보와 일치하는 ID를 찾을 수 없습니다.":(languages==="Chinese"?"找不到与您输入的信息匹配的ID。":"Cannot find an ID that matches the information you entered.")}</aside>

            <Button onClick={handleCancel}>{languages==="Korean"?"확인":(languages==="Chinese"?"确认":"confirm")}</Button>
          </div>
        }
      </Modal>

      <Modal className='modal_change_pass' open={ModalOpen} onCancel={handleCancel} footer={null} centered closable={false}>
        <Forms ref={forms} to_login={to_login}></Forms>
      </Modal>
    </div>
  )
}
